/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 26727
 * Date: 2024-05-24
 * Time: 9:21
 */
class Solution9 {
    public int numSquares(int n) {
        int m = (int)Math.sqrt(n),INF = 0x3f3f3f3f;
        int[][] dp = new int[m+1][n+1];
        dp[0][0] = 0;
        for(int j = 1; j <= n; j++) {
            dp[0][j] = INF;
        }
        for(int i = 1; i <= m; i++) {
            for(int j = 0; j <= n; j++) {
                dp[i][j] = dp[i-1][j];
                if(j >= i*i) {
                    dp[i][j] = Math.min(dp[i][j],dp[i][j-i*i]+1);
                }
            }
        }
        return dp[m][n] >= INF ? 0 : dp[m][n];
    }
}
//优化后
//class Solution {
//    public int numSquares(int n) {
//        int m = (int)Math.sqrt(n),INF = 0x3f3f3f3f;
//        int[] dp = new int[n+1];
//        dp[0] = 0;
//        for(int j = 1; j <= n; j++) {
//            dp[j] = INF;
//        }
//        for(int i = 1; i <= m; i++) {
//            for(int j = i*i; j <= n; j++) {
//                dp[j] = Math.min(dp[j],dp[j-i*i]+1);
//            }
//        }
//        return dp[n];
//    }
//}